import 'package:dio/dio.dart';
import 'package:flutter_yd_simple/Project/Server/Config.dart';

class httpRequest {
  //创建网络请求实力对象
  static final BaseOptions baseOptions = BaseOptions(
    baseUrl: HttpConfig.baseUrl,connectTimeout: HttpConfig.timeout);
  static final Dio dio = Dio(baseOptions);

  static Future<T> request<T>(String url,{String method = "POST",required Map<String,dynamic>params}) async {
    params['token'] = "eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJ1aWQiOjEsInRlbmFudGlkIjoxLCJ1c2VyX3R5cGVfY29kZSI6MSwiZXhwIjoxNzk3NDA3MzIwLCJuYmYiOjE3MTEwMDczMjB9.WGllt5wSJx9OgZt8I95vkXb5UhgqPLrdNMTTAbS8A2w";
    params['tenantSecret'] = 'a1LqP5imgzvjy1kI17DDTw==';
    params['Accept-Language'] = 'zh-Hans-CN;q=1';
    params['User-Agent'] = 'KMpaint/1.0.4 (iPhone; iOS 17.4.1; Scale/2.00)';

    // 1 请求的单独配置
    final Options options = Options(
      contentType: 'application/json',
      method: method,
      headers: params
    );
    String requestStr = HttpConfig.baseUrl + url;
    //2 添加第一个拦截器
    //ignore:unused_local_variable
    Interceptor dInter = InterceptorsWrapper(
      onRequest: (RequestOptions options,RequestInterceptorHandler handler) {
        // 1.在进行任何网络请求的时候，可以添加一个loading显示


        // 2.很多页面的访问必须要求携带Token，那么就可以在这里判断是否有Token

        // 3.对参数进行一些处理，比如序列化处理等


        // 权限验证：比如接口请求后端返回401未授权时可以跳到登录页，403跳到未授权页面；
        // 异常监控：可以在拦截器处理异常，并且上报到异常监控后台或者发送异常预警消息；
        // 缓存接口：可以对于某些接口将请求缓存在本地，设定一定的缓存有效时限，
        // 在时限内重复请求时直接返回本地缓存数据，而无需请求后端接口，降低后端服务器负荷。这块可以参考
        
        print(options.baseUrl);
        print(options.path);
        print(options.uri);

        handler.next(options);
      },onResponse: (response, handler) {

        print(response);
        print("拦截了响应");

        handler.next(response);
      },onError: (error, handler) {

        print(error);
        print("拦截了错误");

        handler.next(error);
      });

    
    // 3 发起网络请求
    try {
      print(requestStr);
      print(options.headers);
      print(params);

      

      Response response = await dio.request(requestStr,queryParameters: params,options: options);
      print(response);
      return response.data;
    } catch (e) {

      print("戳错了????");
      print(e);

      return Future.error(e);
    }
  }
}